from django.shortcuts import render,redirect,HttpResponse,reverse
from django.contrib.auth import authenticate,logout,login
from django.contrib.auth.decorators import login_required
from backend.interactive import task_parse
from backend import models
import json
@login_required
def index(request):
    return render(request, 'index.html')

@login_required
def userinfo(request):
    if request.method == 'POST':
        passwd=request.POST.get('passwd')
        user_obj=models.UserProfile.objects.get(email=request.user)
        user_obj.set_password(passwd)
        user_obj.save()
        return redirect('/login/')
    return render(request,'userinfo.html')

def cmd(request):
    if request.method == 'POST':
        task_obj=task_parse(request)
        res=task_obj.parse()#返回主任务id
        task_dict={}

        for sub_task in res.task_res_set.all():
            task_dict[sub_task.host.host.ip]=[sub_task.id,sub_task.get_status_display(),sub_task.res]

        return HttpResponse(json.dumps(task_dict,ensure_ascii=False))
    return render(request,'cmd.html')

def get_status(request):
    hosts_id=json.loads(request.GET.get('data'))
    res={}
    for host_id in hosts_id:
        host=models.Task_res.objects.get(id=host_id)
        res[host.id]=[host.get_status_display(),host.res,host.host.host.ip]



    return HttpResponse(json.dumps(res,ensure_ascii=False))

def file_mgr(request):
    return render(request,'file_mgr.html')

def login_page(request):
    error_msg=''
    if request.method == 'POST':
        username=request.POST.get('username')
        password=request.POST.get('password')
        user=authenticate(username=username,password=password)
        if user:
            login(request,user)
            return redirect('/')
        else:
            error_msg='用户名或密码错误！！'

    return render(request,'login.html',{'error':error_msg})

def logout_page(request):
    logout(request)
    return redirect('/login/')